<?php declare(strict_types=1);

namespace App\Bac\Handler\RBAC;

use App\Helper\RespHelper;
use App\Bac\Model\RBAC\Admin as DbModel;

class AdminHandler
{

    /**
     * 账户列表
     * @param array $params
     * @return array
     */
    public function list(array $params): array
    {
        $page = (int)@$params['page'] ?: 1;
        $size = (int)@$params['size'] ?: 10;
        $page < 1 && $page = 1;
        ($size < 1 || $size > 50) && $size = 10;
        $username = trim((string)@$params['username']);
        $realname = trim((string)@$params['realname']);
        $query = DbModel::query()->with('roles')->select(['id', 'username', 'realname', 'state', 'created_at', 'updated_at']);
        $username && $query->whereRaw("username like '{$username}%'");
        $realname && $query->whereRaw("realname like '{$realname}%'");
        $total = $query->count();
        $query->offset(($page - 1) * $size)->limit($size);
        $list = $this->formatList($query->get()->toArray());
        return RespHelper::success(['total' => $total, 'rows' => $list]);
    }

    protected function formatList(array $rows): array
    {
        if ($rows) {
            foreach ($rows as &$row) {
                if ($row['roles']) {
                    $row['roles'] = array_unique(array_column($row['roles'], 'role_id'));
                }
            }
        }
        return $rows;
    }

    /**
     * 用户登录
     * @param array $params
     * @return array
     */
    public function login(array $params): array
    {
        $username = $params['username'] ?? null;
        if (!$username) {
            return RespHelper::error('请输入正确的用户名!');
        }
        /** @var DbModel $admin */
        $admin = DbModel::query()->where('username', $username)->first();
        if (!$admin) {
            return RespHelper::error('用户账户不存在!');
        }
        $password = $params['password'] ?? '';
        if (!$admin->validatePassword($password)) {
            return RespHelper::error('用户名或密码错误!');
        }
        if ($admin->state !== DbModel::STATE_NORMAL) {
            return RespHelper::error('账户状态异常，请联系管理员');
        }
        // 更新用户认证秘钥
        $admin->updateAuthKey();
        if ($admin->save()) {
            $resp = $admin->package(true);
            return RespHelper::success($resp);
        }
        return RespHelper::fail('登录失败请稍后重试');
    }

}
